<?php
	/* 
		* +----------------------------------------------------------------
		* +创建时间:2014-9-17下午13:00:00
		* +----------------------------------------------------------------
		* +注　　意:非个人请勿擅自发布商业产品
		* +----------------------------------------------------------------
		* +作　　者:hongweizhiyuan Email:403236160@qq.com
		* +----------------------------------------------------------------
		* +数据库类
		* +----------------------------------------------------------------
	*/
	Class mysql {
		
		private $link_id;
		private $handle;
		private $is_log;
		private $time;
		private $sql; //sql执行语句
		private $result; //执行query命令的结果资源标识
		private $is_error = false; //发现错误是否立即终止,默认true,建议不启用，因为当有问题时用户什么也看不到是很苦恼的
		
		//构造函数
		public function __construct() {
			$this->time = $this->microtime_float();
			require_once("config.db.php");
			$this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]);
			$this->is_log = $db_config["log"];
			if($this->is_log){
				$handle = fopen($db_config["logfilepath"]."dblog.txt", "a+");
				$this->handle=$handle;
			}
		}
		
		//数据库连接
		public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0,$charset='utf8') {
			if( $pconnect==0 ) {
				$this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
				if(!$this->link_id){
					$this->halt("数据库连接失败");
				}
				} else {
				$this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw);
				if(!$this->link_id){
					$this->halt("数据库持久连接失败");
				}
			}
			if(!@mysql_select_db($dbname,$this->link_id)) {
				$this->halt('数据库选择失败');
			}
			@mysql_query("set names ".$charset);
		}
		
		//查询
		public function query($sql) {
			if ($sql == "") {
				$this->show_error("SQL语句错误：", "SQL查询语句为空");
			}
			
			$this->write_log("查询 ".$sql);
			$result = mysql_query($sql,$this->link_id);
			if (!$result) {
				//调试中使用，sql语句出错时会自动打印出来
				if ($this->show_error) {
					$this->show_error("错误SQL语句：", $this->sql);
				}
				} else {
				$this->result = $result;
			}
			return $this->result;
		}
		
		
		//获取一条记录（MYSQL_ASSOC，MYSQL_NUM，MYSQL_BOTH）             
		public function get_one($sql,$result_type = MYSQL_ASSOC) {
			$query = $this->query($sql);
			$rt =& mysql_fetch_array($query,$result_type);
			$this->write_log("获取一条记录 ".$sql);
			return $rt;
		}
		
		//获取全部记录
		public function get_all($sql,$result_type = MYSQL_ASSOC) {
			$query = $this->query($sql);
			$i = 0;
			$rt = array();
			while($row =& mysql_fetch_array($query,$result_type)) {
				$rt[$i]=$row;
				$i++;
			}
			$this->write_log("获取全部记录 ".$sql);
			return $rt;
		}
		
		//插入
		public function insert($table,$dataArray) {
			$field = "";
			$value = "";
			if( !is_array($dataArray) || count($dataArray)<=0) {
				$this->halt('没有要插入的数据');
				return false;
			}
			while(list($key,$val)=each($dataArray)) {
				$field .="$key,";
				$value .="'$val',";
			}
			$field = substr( $field,0,-1);
			$value = substr( $value,0,-1);
			$sql = "insert into $table($field) values($value)";
			$this->write_log("插入 ".$sql);
			if(!$this->query($sql)) return false;
			return true;
		}
		
		//更新
		public function update( $table,$dataArray,$condition="") {
			if( !is_array($dataArray) || count($dataArray)<=0) {
				$this->halt('没有要更新的数据');
				return false;
			}
			$value = "";
			while( list($key,$val) = each($dataArray))
			$value .= "$key = '$val',";
			$value .= substr( $value,0,-1);
			$sql = "update $table set $value where 1=1 and $condition";
			$this->write_log("更新 ".$sql);
			if(!$this->query($sql)) return false;
			return true;
		}
		
		//删除
		public function delete( $table,$condition="") {
			if( empty($condition) ) {
				$this->halt('没有设置删除的条件');
				return false;
			}
			$sql = "delete from $table where 1=1 and $condition";
			$this->write_log("删除 ".$sql);
			if(!$this->query($sql)) return false;
			return true;
		}
		

		
		//获取记录条数
		public function num_rows($results) {
			if(!is_bool($results)) {
				$num = mysql_num_rows($results);
				$this->write_log("获取的记录条数为".$num);
				return $num;
				} else {
				return 0;
			}
		}
		
		
		//释放结果集
		public function free_result() {
			$void = func_get_args();
			foreach($void as $query) {
				if(is_resource($query) && get_resource_type($query) === 'mysql result') {
					return mysql_free_result($query);
				}
			}
			$this->write_log("释放结果集");
		}
		
		//获取最后插入的id
		public function insert_id() {
			$id = mysql_insert_id($this->link_id);
			$this->write_log("最后插入的id为".$id);
			return $id;
		}
		
		//关闭数据库连接
		protected function close() {
			$this->write_log("已关闭数据库连接");
			return @mysql_close($this->link_id);
		}
		
		//错误提示
		private function halt($msg='') {
			$msg .= "\r\n".mysql_error();
			$this->write_log($msg);
			die($msg);
		}
		
		//析构函数
		public function __destruct() {
			$this->free_result();
			$use_time = ($this-> microtime_float())-($this->time);
			$this->write_log("完成整个查询任务,所用时间为".$use_time);
			if($this->is_log){
				fclose($this->handle);
			}
		}
		
		//写入日志文件
		public function write_log($msg=''){
			if($this->is_log){
				$text = date("Y-m-d H:i:s")." ".$msg."\r\n";
				fwrite($this->handle,$text);
			}
		}
		
		//获取毫秒数
		public function microtime_float() {
			list($usec, $sec) = explode(" ", microtime());
			return ((float)$usec + (float)$sec);
		}
		
		//根据insert,update,delete执行结果取得影响行数
		public function db_affected_rows() {
			return mysql_affected_rows();
		}
		
		
		//取得 MySQL 服务器信息
		public function mysql_server($num = '') {
			switch ($num) {
				case 1 :
				return mysql_get_server_info(); //MySQL 服务器信息
				break;
				
				case 2 :
				return mysql_get_host_info(); //取得 MySQL 主机信息
				break;
				
				case 3 :
				return mysql_get_client_info(); //取得 MySQL 客户端信息
				break;
				
				case 4 :
				return mysql_get_proto_info(); //取得 MySQL 协议信息
				break;
				
				default :
				return mysql_get_client_info(); //默认取得mysql版本信息
			}
		}
		
		//输出显示sql语句
		public function show_error($message = "", $sql = "") {
			if (!$sql) {
				echo "<font color='red'>" . $message . "</font>";
				echo "<br />";
				} else {
				echo "<fieldset>";
				echo "<legend>错误信息提示:</legend><br />";
				echo "<div style='font-size:14px; clear:both; font-family:Verdana, Arial, Helvetica, sans-serif;'>";
				echo "<div style='height:20px; background:#000000; border:1px #000000 solid'>";
				echo "<font color='white'>错误号：12142</font>";
				echo "</div><br />";
				echo "错误原因：" . mysql_error() . "<br /><br />";
				echo "<div style='height:20px; background:#FF0000; border:1px #FF0000 solid'>";
				echo "<font color='white'>" . $message . "</font>";
				echo "</div>";
				echo "<font color='red'><pre>" . $sql . "</pre></font>";
				$ip = $this->getip();
				if ($this->bulletin) {
					$time = date("Y-m-d H:i:s");
					$message = $message . "\r\n$this->sql" . "\r\n客户IP:$ip" . "\r\n时间 :$time" . "\r\n\r\n";
					
					$server_date = date("Y-m-d");
					$filename = $server_date . ".txt";
					$file_path = "error/" . $filename;
					$error_content = $message;
					//$error_content="错误的数据库，不可以链接";
					$file = "error"; //设置文件保存目录
					
					//建立文件夹
					if (!file_exists($file)) {
						if (!mkdir($file, 0777)) {
							//默认的 mode 是 0777，意味着最大可能的访问权
							die("upload files directory does not exist and creation failed");
						}
					}
					
					//建立txt日期文件
					if (!file_exists($file_path)) {
						
						//echo "建立日期文件";
						fopen($file_path, "w+");
						
						//首先要确定文件存在并且可写
						if (is_writable($file_path)) {
							//使用添加模式打开$filename，文件指针将会在文件的开头
							if (!$handle = fopen($file_path, 'a')) {
								echo "不能打开文件 $filename";
								exit;
							}
							
							//将$somecontent写入到我们打开的文件中。
							if (!fwrite($handle, $error_content)) {
								echo "不能写入到文件 $filename";
								exit;
							}
							
							//echo "文件 $filename 写入成功";
							
							echo "——错误记录被保存!";
							
							//关闭文件
							fclose($handle);
							} else {
							echo "文件 $filename 不可写";
						}
						
						} else {
						//首先要确定文件存在并且可写
						if (is_writable($file_path)) {
							//使用添加模式打开$filename，文件指针将会在文件的开头
							if (!$handle = fopen($file_path, 'a')) {
								echo "不能打开文件 $filename";
								exit;
							}
							
							//将$somecontent写入到我们打开的文件中。
							if (!fwrite($handle, $error_content)) {
								echo "不能写入到文件 $filename";
								exit;
							}
							
							//echo "文件 $filename 写入成功";
							echo "——错误记录被保存!";
							
							//关闭文件
							fclose($handle);
							} else {
							echo "文件 $filename 不可写";
						}
					}
					
				}
				echo "<br />";
				if ($this->is_error) {
					exit;
				}
			}
			echo "</div>";
			echo "</fieldset>";
			
			echo "<br />";
		}
		
		
		//获得IP地址
		function getip() {
			if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
				$ip = getenv("HTTP_CLIENT_IP");
			} else
			if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
				$ip = getenv("HTTP_X_FORWARDED_FOR");
			} else
			if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
				$ip = getenv("REMOTE_ADDR");
			} else
			if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
				$ip = $_SERVER['REMOTE_ADDR'];
				} else {
				$ip = "unknown";
			}
			return ($ip);
		}
		
		/* 
			函数名称：inject_check() 
			函数作用：检测提交的值是不是含有SQL注射的字符，防止注射，保护服务器安全 
			参　　数：$sql_str: 提交的变量 
			返 回 值：返回检测结果，ture or false 
		*/ 
		function inject_check($sql_str) { 
			$check = eregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);
			if ($check) {
				echo "输入非法注入内容！";
				exit ();
				} else {
				return $sql_str;
			}
		}
		
	
		//end
	}
	
?>